<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Tree;

class CategoryController extends Controller {

    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index() {
        return Admin::content(function (Content $content) {

                    $content->header('商品分类');
                    $content->body($this->tree());
                });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id) {
        return Admin::content(function (Content $content) use ($id) {

                    $content->header('编辑分类');

                    $content->body($this->form()->edit($id));
                });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create() {
        return Admin::content(function (Content $content) {

                    $content->header('创建分类');

                    $content->body($this->form());
                });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form() {
        return Admin::form(Category::class, function (Form $form) {

                    $form->display('id', 'ID');
                    $form->text('order', '排序')->rules('required|numeric');
                    $form->select('parent_id', '上级分类')->options(Category::selectOptions());
                    $form->text('title', '分类名')->rules('required');
                    $form->image('logo', '分类logo');
                    $form->textarea('desc', '描述')->rules('required');
                    $form->display('created_at', 'Created At');
                    $form->display('updated_at', 'Updated At');
                });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function tree() {
        return Category::tree(function ($tree) {
                    $tree->branch(function ($branch) {
                        if ($branch['logo']) {
                            $src = $branch['logo'];
                            $logo = "<img src='$src' style='max-width:30px;max-height:30px' class='img'/>";

                            return "{$branch['id']} - {$branch['title']} $logo";
                        }
                        return "{$branch['id']} - {$branch['title']}";
                    });
                });
    }

}
